package cn.csc.module.distribute.mq.consumer;


import cn.csc.module.distribute.api.distributor.dto.DistributorReqDTO;
import cn.csc.module.distribute.api.order.dto.DistributeOrderDTO;
import cn.csc.module.distribute.convert.order.DistributeOrderConvert;
import cn.csc.module.distribute.dal.dataobject.downline.DistributeDownlineDO;

import cn.csc.module.distribute.dal.mysql.downline.DistributeDownlineMapper;
import cn.csc.module.distribute.service.distributor.DistributorService;
import cn.csc.module.distribute.service.order.DistributeOrderService;


import cn.csc.module.order.message.OrderSubmitMessage;
import cn.csc.module.product.api.category.CategoryApi;
import cn.csc.module.product.api.category.dto.CategoryRespDTO;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Collectors;

import static cn.csc.framework.common.util.json.JsonUtils.toJsonString;

/**
 * 订单支付成功，计算待入账佣金
 *
 * @author liuchuang
 * @version 1.0
 * @modify
 * @since 2025/4/27 15:46
 */
@Slf4j
@Component
public class OrderSubmitConsumer {

    @Resource
    private DistributeDownlineMapper distributeDownlineMapper;
    @Resource
    private DistributeOrderService distributeOrderService;
    @Resource
    private CategoryApi categoryApi;
    @Resource
    private DistributorService distributorService;

    /**
     * 订单支付成功，计算佣金
     * 消费 {@link OrderSubmitMessage} 消息
     * message： the input argument
     */
    @Bean
    public Consumer<List<OrderSubmitMessage>> orderSubmit() {
        return message -> {
            log.info("OrderSubmitConsumer订单支付成功消息开始: {}", toJsonString(message));
            try {
                //message 数据类型LinkedHashMap 要强转类型
                List<Map<String, Object>> list = new ObjectMapper().readValue(toJsonString(message), List.class);
                //组合后的分销系统订单信息
                List<DistributeOrderDTO> createReqDtoList =new ArrayList<>();
                for (Map<String, Object> map : list) {
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    DistributeOrderDTO distributeOrderDTO = new DistributeOrderDTO();
                    distributeOrderDTO.setOrderId(new BigInteger((String)map.get("orderId")))
                            .setAmount(new BigDecimal(String.valueOf(map.get("amount"))))
                            .setChildId(new BigInteger((String)map.get("userId")))
                            .setOrderItemId(new BigInteger((String)map.get("orderItemId")))
                            .setCategoryId((String)map.get("categoryId"))
                            .setOrderStatus(Integer.parseInt(String.valueOf(map.get("orderStatus"))))
                            .setPayTime(LocalDateTime.parse((String)map.get("payTime"),formatter));
                    createReqDtoList.add(distributeOrderDTO);
                }

                log.info("OrderSubmitConsumer-createReqDtoList: {}", createReqDtoList);
                BigInteger userId=new BigInteger(String.valueOf(createReqDtoList.get(0).getChildId()));
                log.info("OrderSubmitConsumer-list-userId: {}", userId);
                DistributeDownlineDO downlineDO = distributeDownlineMapper.selectByChildId(userId);
                log.info("OrderSubmitConsumer-downlineDO: {}", downlineDO);
                // 分销订单
                if (downlineDO != null) {
                    //创建分账订单
                    //分销员上线的用户id
                    BigInteger parentUserId= distributorService.getDistributor(downlineDO.getParentId()).getUserId();
                    //根据类目Id取出对应的佣金比例
                    List<BigInteger> lastCategoryIds =createReqDtoList.stream()
                            .map(item -> {
                                String[] parts = item.getCategoryId().split(",");
                                return parts[parts.length - 1];
                            }).collect(Collectors.toList()).stream()
                            .map(BigInteger::new)  // 字符串转BigInteger:ml-citation{ref="6" data="citationList"}
                            .collect(Collectors.toList());
                    log.info("OrderSubmitConsumer-createReqDtoList: {}", createReqDtoList);
                    List<CategoryRespDTO> categoryList = categoryApi.listCategoryIds(lastCategoryIds).getCheckedData();
                    log.info("OrderSubmitConsumer-categoryList: {}", categoryList);
                    createReqDtoList.forEach(orderDTO -> {
                        CategoryRespDTO cdto = categoryList.stream().filter(c -> orderDTO.getCategoryId().contains(c.getId().toString())).findFirst().orElse(null);
                        Integer rate = cdto.getCommissionRate();
                        log.info("OrderSubmitConsumer-rate: {}",rate);
                        if (rate != null) {
                            orderDTO.setCommissionRate(rate);  // 匹配成功时赋值
                        } else {
                            // 无匹配时的处理逻辑（如保留原值或设置默认值）
                            orderDTO.setCommissionRate(0);
                        }
                        orderDTO.setUserId(parentUserId.longValue());//上级
                    });
                    log.info("OrderSubmitConsumer-createReqDtoListRate: {}", createReqDtoList);
                    distributeOrderService.createOrderBatch(createReqDtoList);
                    // 订单支付，计算待入账佣金
                    BigDecimal amount = createReqDtoList.stream()
                            .map(dto -> dto.getAmount().multiply(new BigDecimal(dto.getCommissionRate()).divide(new BigDecimal(100))))
                            .reduce(BigDecimal.ZERO, BigDecimal::add)  // 累加所有项
                            .setScale(2, RoundingMode.HALF_UP);  // 最终结果保留两位小数

                    DistributorReqDTO distributorReqDTO = new DistributorReqDTO();
                    distributorReqDTO.setUserId(parentUserId)
                            .setAmount(amount);
                    log.info("OrderSubmitConsumer-distributorReqDTO: {}", distributorReqDTO);
                    distributorService.pening(distributorReqDTO);
                }

            } catch (Exception e) {
                log.error("订单支付成功消息消费失败:{}", message, e);
            }
        };
    }

}
